
import LanguageMng from "../Managers/LanguageMng";
import LogicConfigTs from "./LogicConfigTs";

cc.Class({
    extends: cc.Component,

    properties: {
        //管理本次DealInfo的数据，下一局开始之后，仍然会存在，供玩家查看上一局记录
        //直到有人Finish/自己Drop的时候清空，装载下一次数据
        dealInfoData:null,
    },

    initDealInfoData:function (users,showScoreWhenWaiting) {
        let resultDatas = []
        for(let key in users){
            let userObj = users[key]
            if(!userObj) continue

            resultDatas[userObj.id] = {}
            resultDatas[userObj.id].name = userObj.name
            resultDatas[userObj.id].id = userObj.id
            resultDatas[userObj.id].result = LanguageMng.getSentence(176)   //Waiting
            resultDatas[userObj.id].score = null
            let totalScoreStr = !showScoreWhenWaiting?cc.gg.gameDataUtil.getStringOfRupee(userObj.score):userObj.score
            resultDatas[userObj.id].totalScore = totalScoreStr//cc.gg.dataMgr.room.getTotalScore(userObj.id)
        }

        this.dealInfoData = resultDatas
    },

    setDealInfoWinner:function (id) {
        for(let key in this.dealInfoData){
            let row = this.dealInfoData[key]
            if(row.id === id){
                row.result = "%win%"
            }else {
                row.result = "%lose%"
            }
        }
    },

    setDealInfoScore:function (id,score) {
        for(let key in this.dealInfoData){
            let row = this.dealInfoData[key]
            if(row.id === id){
                row.score = score
                return
            }
        }
    },

    setDealInfoTotalScore:function (id,totalScore) {
        for(let key in this.dealInfoData){
            let row = this.dealInfoData[key]
            if(row.id === id){
                row.totalScore = totalScore
                return
            }
        }
    },

    // setDealInfoData:function (data) {
    //     this._dealInfoData = data
    // },
    //
    // getDealInfoData:function () {
    //     return this._dealInfoData
    // },

    ctor(){

        //restore room ids that player quit by himself
        this.closedRooms = []

        this.shopBuy = [
            {pack_id:1,price:10,coin:1000},
            {pack_id:2,price:50,coin:5000},
            {pack_id:3,price:100,coin:10000},
            {pack_id:4,price:500,coin:50000},
            {pack_id:5,price:1000,coin:100000},
            {pack_id:6,price:5000,coin:500000},
            {pack_id:7,price:10000,coin:1000000},
            {pack_id:8,price:50000,coin:5000000},
        ]

        this.shopWithDraw = [
            {pack_id:0,price:10,coin:1000},
            {pack_id:1,price:50,coin:5000},
            {pack_id:2,price:100,coin:10000},
            {pack_id:3,price:500,coin:50000},
            {pack_id:4,price:1000,coin:100000},
            {pack_id:5,price:5000,coin:500000},
        ]

        this.showRupee = true
        let naticeShowRupee = this.getShowRupee()
        if(!naticeShowRupee || typeof naticeShowRupee === "undefined" || !parseInt(naticeShowRupee)){
            this.showRupee = false
        }else {
            this.showRupee = true
        }
        //test
        if (!cc.sys.isNative) {
            this.showRupee = true
        }

        this.coinIcon = null
        this.cashIcon = null
        this.rupeeIcon = null


        this.keyboardUpCbs = {}
        this.keyboardDownCbs = {}
        // this.localFaceColor = [
        //     {id:1,color:}
        // ]
        //User is login from login page
        this.isRegister = false
    },

    initAllCoinIcon:function (coinIcon, cashIcon, rupeeIcon) {
        this.coinIcon = coinIcon
        this.cashIcon = cashIcon
        this.rupeeIcon = rupeeIcon
    },

    getStringOfRupee:function (coinValue) {
        if(this.showRupee){
            if(typeof coinValue === 'number'){
                return "₹ " + coinValue/100
            }
        }

        return coinValue
    },

    getStringOfRupeeWithoutSymbol:function (coinValue) {
        if(this.showRupee){
            if(typeof coinValue === 'number'){
                return coinValue/100
            }
        }

        return coinValue
    },

    getStringOfRupeeK:function (coinValue) {
        if(this.showRupee){
            if(typeof coinValue === 'number'){
                if(coinValue >= 1000){
                    let kstr = coinValue/100000
                    return kstr + "K ₹"
                }else {
                    return coinValue/100 + "₹"
                }
            }
        }

        return coinValue
    },

    addKeyboardUpCb:function (key,cb) {
        this.keyboardUpCbs[key] = cb
    },

    removeKeyboardUpCb:function (key) {
        this.keyboardUpCbs[key] = null
    },

    addKeyboardDownCb:function (key,cb) {
        this.keyboardDownCbs[key] = cb
    },

    removeKeyboardDownCb:function (key) {
        this.keyboardDownCbs[key] = null
    },


    getWithDrawObj:function (packId) {
        for(let i=0;i<this.shopWithDraw.length;i++){
            let obj = this.shopWithDraw[i]
            if(obj.pack_id === packId)
                return obj
        }
        return null
    },

    // onLoad () {},

    start () {

    },

    // update (dt) {},

    getCardValArrayFromPokerObj:function (pokerArray,exceptPokerObj) {
        let vals = []
        for(let i=0;i<pokerArray.length;i++){
            if(pokerArray[i] === exceptPokerObj) continue
            vals.push(pokerArray[i].poker)
        }
        return vals
    },

    getCardsArrayFromBottoms:function (bottoms,exceptPokerObj) {
        let cardsArray = []
        for(let i=0;i<bottoms.length;i++){
            let cards = this.getCardValArrayFromPokerObj(bottoms[i].pokers,exceptPokerObj)
            if(cards.length)
                cardsArray.push(cards)
        }
        return cardsArray
    },

    //Used for guild,try to find real poker node by fake poker node'name
    setFakeNodePosition:function (nodes) {
        for(let i=0;i<nodes.length;i++){
            let node = nodes[i]
            node.active = true
            let pokerValue = parseInt(node.name)

            let pokerNode = cc.gg.tpgMgr.getPokerNodeByPokerValue(pokerValue)
            if(!pokerNode){
                cc.warn("UnException ,cannot find poker:",pokerValue)
            }
            let worPos = pokerNode.parent.convertToWorldSpaceAR(pokerNode.position)
            let localPos = node.parent.convertToNodeSpaceAR(worPos)
            node.position = localPos
            cc.log("localpos;",localPos)
        }
    },

    //校验手牌和服务端存储的牌型，得到最终恢复的正确牌组
    getRealRestoreCards:function (resCards,handCards) {
        if(!resCards){
            resCards = []
        }

        handCards = [].concat(handCards)
        let realResCards = []
        for(let i=0;i<resCards.length;i++){
            let array = resCards[i]
            let newArray = []
            for(let j=0;j<array.length;j++){
                let v = array[j]
                if(this.exsistsInPlanarArray(handCards,v)){
                    newArray.push(v)
                }else {

                }
            }
            realResCards.push(newArray)
        }
        if(handCards.length > 0){
            realResCards.push(handCards)
        }

        return realResCards
    },

    exsistsInPlanarArray:function (planarArray,elem) {

        let idx = planarArray.indexOf(elem)
        if(idx > -1){
            planarArray.splice(idx,1)
            return true
        }
        return false
    },

    refreshPlayerInfo:function (successCb) {
        cc.gg.httpUtil.httpGet('/user/profile/get',null,function (result) {
            if(!result.succ){
                cc.gg.httpUtil.setUserToken(null)
                cc.gg.gameDataUtil.goToLogin(true)
            }else {
                if(successCb){
                    result.data.face_bg = Math.random()*1000000
                    successCb(result)
                }
            }
        }.bind(this))
    },

    convertPokerObjGroupToArray:function (group) {
        let array = []
        for(let i=0;i<group.length;i++){
            let tmpArr = group[i]
            for(let j=0;j<tmpArr.length;j++){
                array.push(tmpArr[j])
            }
        }
        return array
    },

    removeHandPokerObj:function (array, pokerId) {
        for(let i=0;i<array.length;i++){
            let poker = array[i]
            if(poker.id === pokerId){
                array.splice(i,1)
                cc.log("=======>>>打出一张牌，还剩：",array.length)
                return true
            }
        }
        cc.log("=======>>>打出一张牌失败：",array.length)
        return false
    },

    addHandPokerObj:function (array, pokerObj) {
        array.push(pokerObj)
        cc.log("=======>>>摸了一张牌，现在有：",array.length)
    },

    getPakageChannel:function () {

        if(cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID){
            var channel = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getChannel","()Ljava/lang/String;");
            console.log("渠道：",channel)
            return channel;
        }else if ( cc.sys.os == cc.sys.OS_IOS ){
            return "ios_channel"
            // var nPower = jsb.reflection.callStaticMethod("AppController", "getBatteryPercent");
            // return nPower;
        }else {
            if(CC_DEBUG){
                return "debug"
            }else {
                let params = this.getRequest()
                let tdChannel = params["td_channelid"] || "unknown"
                return tdChannel
            }
        }
    },

    getRequest() {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            if (str.indexOf("&") != -1) {
                let strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                }
            } else {
                theRequest[str.split("=")[0]] = unescape(str.split("=")[1]);
            }
        }
        return theRequest;
    },

    getShowRupee:function () {
        if(cc.sys.isNative && cc.sys.os == cc.sys.OS_ANDROID){
            var channel = jsb.reflection.callStaticMethod("org/cocos2dx/javascript/AppActivity", "getShowRupee","()I");
            console.log("显示卢比：",channel)
            return channel;
        }else if ( cc.sys.os == cc.sys.OS_IOS ){
            return "0"
            // var nPower = jsb.reflection.callStaticMethod("AppController", "getBatteryPercent");
            // return nPower;
        }else {
            return "0"
        }
    },

    goToLobby:function (setHorizontal) {
        if(setHorizontal) cc.gg.baseUtil.setLandscape(1)
        cc.director.loadScene("LobbyBlue",function () {
            // if(setHorizontal) cc.gg.baseUtil.setLandscape(1)
            cc.gg.tdUtil.doSendTdEvent("open_lobby",null)
        })
    },

    goToLogin:function () {
        if(LogicConfigTs.IS_LOGIN_VERTICAL){
            cc.gg.baseUtil.setLandscape(2)
        }else {
            cc.gg.baseUtil.setLandscape(1)
        }
        cc.director.loadScene(LogicConfigTs.SCENENAME_LOGIN)
    },

    setIsNewComer:function (gameGlobalId) {
        cc.sys.localStorage.setItem("user_setting_is_new_comer"+gameGlobalId,1)
    },

    getIsNewComer:function (gameGlobalId) {
        let is = cc.sys.localStorage.getItem('user_setting_is_new_comer'+gameGlobalId)
        return !is
    },


    setReadWalletNotice:function (gameGlobalId) {
        cc.sys.localStorage.setItem("user_setting_read_wallet"+gameGlobalId,1)
    },

    getReadWalletNotice:function (gameGlobalId) {
        let is = cc.sys.localStorage.getItem('user_setting_read_wallet'+gameGlobalId)
        return is
    },

    goToTwoPlayerGame:function (sceneCb) {
        // cc.gg.gameDataUtil.scene = cc.SCENE.TABLE
        cc.find("Canvas").emit("msgwatcher_add",function () {
            if(cc.gg.dataMgr.getPlayerUser() || cc.gg.dataMgr.playGuild){
                cc.director.loadScene('TwoPlayerGame',function () {
                    cc.gg.tdUtil.doSendTdPageStart('TwoPlayerGame')
                    if(sceneCb) sceneCb()
                }.bind(this))
                return true
            }
            return false
        }.bind(this))
    },



    goToSixPlayerGame:function (sceneCb) {
        // cc.gg.gameDataUtil.scene = cc.SCENE.TABLE
        cc.find("Canvas").emit("msgwatcher_add",function () {
            if(cc.gg.dataMgr.getPlayerUser() || cc.gg.dataMgr.playGuild){
                cc.director.loadScene('SixPlayerGame',function () {
                    cc.gg.tdUtil.doSendTdPageStart('SixPlayerGame')
                    if(sceneCb) sceneCb()
                }.bind(this))
                return true
            }
            return false
        }.bind(this))
    },
});
